/* eslint-disable import/prefer-default-export */
// import fetch from 'dva/fetch';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

const persistConfig = {
  key: 'dva',
  storage,
  whitelist: ['login'],
};

const persistEnhancer = () => createStore => (reducer, initialState, enhancer) => {
  const store = createStore(persistReducer(persistConfig, reducer), initialState, enhancer);
  const persist = persistStore(store);
  return { ...store, persist };
};

const socketReducer = reducer => (state, action) => {
  const newState = reducer(state, action);
  const { routing, menu, login, loading, global, setting, user, workplace, socket } = state;

  switch (action.type) {
    case 'CLEAR_STORE':
      return {
        routing,
        menu,
        login,
        loading,
        global,
        setting,
        user,
        workplace,
        socket,
      };
    default:
      return newState;
  }
};

export const dva = {
  config: {
    onReducer: socketReducer,
    extraEnhancers: [persistEnhancer()],
    onError(e) {
      e.preventDefault();
      console.error(e.message);
    },
  },
};

// let authRoutes = null;

// function ergodicRoutes(routes, authKey, authority) {
//   routes.forEach(element => {
//     if (element.path === authKey && element.authority) {
//       Object.assign(element.authority, authority || []);
//     } else if (element.routes) {
//       ergodicRoutes(element.routes, authKey, authority);
//     }
//     return element;
//   });
// }

// export function patchRoutes(routes) {
//   Object.keys(authRoutes).map(authKey =>
//     ergodicRoutes(routes, authKey, authRoutes[authKey].authority)
//   );
//   window.g_routes = routes;
// }

// export function render(oldRender) {
//   fetch('/api/auth_routes')
//     .then(res => res.json())
//     .then(ret => {
//       authRoutes = ret;
//       oldRender();
//     });
// }
